// src/Register.tsx
import { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './App.css';

function Register() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false); // 控制按钮 loading 状态

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const response = await fetch('/api/users/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
          inviteCode: values.inviteCode,
        }),
      });

      const result = await response.json();

      if (response.ok && result.message === '注册成功') {
        // ✅ 注册成功
        message.success('注册成功！');
        navigate('/login'); // 跳转到登录页
      } else {
        // ❌ 注册失败
        const errorMsg = result.message || '注册失败，请稍后重试';
        message.error(errorMsg);
      }
    } catch (error) {
      console.error('网络错误:', error);
      message.error('网络异常，请检查后端服务是否开启');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="login-page"
      style={{
        backgroundImage: "url('/background.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        height: '100vh',
        display: 'flex',
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingRight: '10%',
        boxSizing: 'border-box',
      }}
    >
      <div className="login-form">
        {/* Logo */}
        <div className="logo">
          <img src="/logo.png" alt="食悟 Logo" />
        </div>

        {/* 注册表单 */}
        <Form
          name="register"
          onFinish={onFinish}
          initialValues={{ remember: true }}
          style={{ width: '100%' }}
        >
          {/* 邀请码输入框 */}
          <Form.Item
            name="inviteCode"
            rules={[{ required: true, message: '请输入邀请码!' }]}
          >
            <Input
              prefix={<LockOutlined style={{ color: '#e8d9c7' }} />}
              placeholder="请输入邀请码"
              style={{
                backgroundColor: '#FFFFFF',
                borderColor: '#e8d9c7',
                borderWidth: '2px',
                borderRadius: '20px',
                height: '42px',
              }}
            />
          </Form.Item>

          {/* 用户名 */}
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input
              prefix={<UserOutlined style={{ color: '#e8d9c7' }} />}
              placeholder="请输入用户名/账号"
              style={{
                backgroundColor: '#FFFFFF',
                borderColor: '#e8d9c7',
                borderWidth: '2px',
                borderRadius: '20px',
                height: '42px',
              }}
            />
          </Form.Item>

          {/* 密码 */}
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#e8d9c7' }} />}
              placeholder="请输入密码"
              style={{
                backgroundColor: '#FFFFFF',
                borderColor: '#e8d9c7',
                borderWidth: '2px',
                borderRadius: '20px',
                height: '42px',
              }}
            />
          </Form.Item>

          {/* 注册按钮 */}
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              loading={loading} // 显示 loading 状态
              style={{
                backgroundColor: '#e8d9c7',
                borderColor: '#e8d9c7',
                color: '#555',
                fontWeight: 'bold',
                padding: '12px 24px',
                height: '42px',
              }}
            >
              注册
            </Button>
          </Form.Item>
        </Form>

        {/* 登录链接 */}
        <a href="/login" className="register-link">
          点击登录
        </a>
      </div>
    </div>
  );
}

export default Register;